package 日期算法.日期之间隔几天;

/**
 * TODO
 *
 * @className: rqzjgjt
 * @description: TODO
 * @author: 等什么柠檬君
 * @date: 2022-05-05 19:18
 **/
public class rqzjgjt {
    public static void main(String[] args) {

        System.out.println(daysBetweenDates("2019-06-29", "2019-06-30"));
    }
    public static int daysBetweenDates(String date1, String date2) {
        final String[] split1 = date1.split("-");
        final String[] split2 = date2.split("-");
        int year1 = Integer.parseInt(split1[0]);
        int month1 = Integer.parseInt(split1[1]);
        int day1 = Integer.parseInt(split1[2]);

        int year2 = Integer.parseInt(split2[0]);
        int month2 = Integer.parseInt(split2[1]);
        int day2 = Integer.parseInt(split2[2]);
        return Math.abs(getDays(year2, month2, day2)-getDays(year1, month1, day1));
    }

    public static int getDays(int year, int month, int day){
        int[] monthDays =  { 0,
                31, 28, 31, 30, 31, 30,
                31, 31, 30, 31, 30, 31
        };
        int days = day - 1;
        for (int i = 1971; i < year; i++) {
            if (isLeapYear(i)){
                days += 366;
            }else {
                days += 365;
            }
        }
        if (month > 1){
            for (int i = 1; i < month; i++) {
                if (isLeapYear(year) && i==2){
                    days += 29;
                    continue;
                }
                days  += monthDays[i];
            }
        }
        return days;
    }

    public static boolean isLeapYear(int y){
        return ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0));
    }
}
